<?php
/**
 * @brief 支付宝插件类
 * @class Alipay
 * @package App
 * @subpackage  Driver.Payment
 * @author cjli
 */
class Alipay extends Payment implements Payment_Interface, Payment_Server_Interface
{
	public function __construct()
	{
		$this->_paymentInfo = PaymentModel::get_payment_info('Alipay');
	}
	
/*  public function getSettingFields()
  {
    return array(
      'alipay_account' => 'caiwu@ownonly.com',
      'alipay_key' => 'h2nkyzooribx4gnw86bt3rrnsiifgn50',
      'alipay_partner' => '2088611729019624',
      'alipay_pay_method' => array(
        'name' => '使用即时到帐交易接口',
        'type' => 'select',
        'options' => array(
          '0' => '使用标准双接口',
          '1' => '使用担保交易接口',
          '2' => '使用即时到帐交易接口',
        ),
        'default' => '2',
      ),
    );
  }*/

    public function getSettingFields()
    {

		return array(
		  'alipay_account' => '支付宝账号',
		  'alipay_key' => 'KEY',
		  'alipay_partner' => '合作者ID',
		  'alipay_pay_method' => array(
			'name' => '交易接口',
			'type' => 'select',
			'options' => array(
			  '0' => '使用标准双接口',
			  '1' => '使用担保交易接口',
			  '2' => '使用即时到帐交易接口',
			),
			'default' => '2',
		  ),
		);
    }  
  
  public function getSubmitForm($orderInfo)
  {
    $charset = 'utf-8';

        $real_method = $this->_paymentInfo['config']['alipay_pay_method'];
          //dump($real_method);exit;
        switch ($real_method){
            case '0':
                $service = 'trade_create_by_buyer';
                break;
            case '1':
                $service = 'create_partner_trade_by_buyer';
                break;
            case '2':
                $service = 'create_direct_pay_by_user';
                break;
        }

       // $agent = 'C4335319945672464113';
       $extend_param = 'isv^sh22';
        $parameter = array(
            //'agent'             => $agent,
            'extend_param'      => $extend_param,
            'service'           => $service,
            'partner'           => $this->_paymentInfo['config']['alipay_partner'],
            '_input_charset'    => $charset,
            'notify_url'        => url('payment/notice', array('pay' => 'Alipay')),
            'return_url'        => url('payment/callback', array('pay' => 'Alipay')),
            /* 业务参数 */
            'subject'           => $orderInfo['order_sn'],
            'out_trade_no'      => $orderInfo['order_sn'] .'-'.rand(1,999),
            'price'             => $orderInfo['pay_amount'],
            'quantity'          => 1,
            'payment_type'      => 1,
            /* 物流参数 */
            'logistics_type'    => 'EXPRESS',
            'logistics_fee'     => 0,
            'logistics_payment' => 'BUYER_PAY_AFTER_RECEIVE',
            /* 买卖双方信息 */
            'seller_email'      => $this->_paymentInfo['config']['alipay_account']
        );
     //dump($parameter);exit;
        ksort($parameter);
        reset($parameter);

        $param = '';
        $sign  = '';

        foreach ($parameter AS $key => $val)
        {
            $param .= "$key=" .urlencode($val). "&";
            $sign  .= "$key=$val&";
        }

        $param = substr($param, 0, -1);
        $sign  = substr($sign, 0, -1). $this->_paymentInfo['config']['alipay_key'];
        //$sign  = substr($sign, 0, -1). ALIPAY_AUTH;

        $submiturl = 'https://www.alipay.com/cooperate/gateway.do?'.$param. '&sign='.md5($sign).'&sign_type=MD5';
        $html = array(
          '<form id="frm" action="' . $submiturl . '" method="post">',
          '<input type="submit" class="pay_button" value="' . L('_PAY_NOW_') . '">',
          '</form>',
        );
        return implode(PHP_EOL, $html);
  }


  public function checkPost(){
    $flag = true;
    if (!empty($_POST))
    {
        foreach($_POST as $key => $data)
        {
            $_GET[$key] = $data;
        }
    }
    if(isset($_GET['_URL_'])){
       unset($_GET['_URL_']);
    }
    unset($_GET['pay']);

    $seller_email = rawurldecode($_GET['seller_email']);
    //$order_id = str_replace($_GET['subject'], '', $_GET['out_trade_no']);
    //$order_id = trim($order_id);
    $order_id = OrderModel::get_orderId_by_orderSn($_GET['subject']);

    /* 检查支付的金额是否相符 */
    if (!$this->checkMoney($order_id, $_GET['total_fee']))
    {
        $flag = false;
    }

    /* 检查数字签名是否正确 */
    ksort($_GET);
    reset($_GET);

    $sign = '';
    foreach ($_GET AS $key=>$val)
    {
        if ($key != 'sign' && $key != 'sign_type' && $key != 'code')
        {
            $sign .= "$key=$val&";
        }
    }
    
    $sign = substr($sign, 0, -1) . $this->_paymentInfo['config']['alipay_key'];
    //$sign = substr($sign, 0, -1) . ALIPAY_AUTH;

    if (md5($sign) != $_GET['sign'])
    {
        $flag = false;
    }
    return $flag;
  }

  public function callback()
  {

  	$result = array(
        'verified' => false,
        'paidAmount' => $_GET['total_fee'],
        'paymentId' => $_GET['trade_no'],
        'orderNumber' => $_GET['subject'],
        'updateOrderStatus' => false,
        'message' => '',
      );


	/* 验证 */
  $flag = $this->checkPost();
	if ($flag) {
		if ($_GET['trade_status'] == 'WAIT_SELLER_SEND_GOODS' || $_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
			$result['verified'] = true;
			$result['updateOrderStatus'] = true;
			$result['message'] = L('_PAYMENT_SUCCESS_');
		} else {
			$result['message'] = L('_PAYMENT_FAILURE_');
		}
	} else {
		$result['message'] = L('_PAYMENT_VALIDATION_FAILS_');
	}
	return $result;
  }

/**
 * 检查支付的金额是否与订单相符
 *
 * @access  public
 * @param   string   $order_id      订单号
 * @param   float    $money       支付接口返回的金额
 * @return  true
 */
	private function checkMoney($order_id, $money)
	{
			$order_db = D('orders');
			$amount = $order_db->where(array('id' => $order_id))->getField('pay_amount');
      $amount = currency($amount, null, false, 'CNY');
	    if ($money == $amount)
	    {
	        return true;
	    }
	    else
	    {
	        return false;
	    }
	}

    public function serverCallback()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && $flag = $this->checkPost()) {
          $result = array(
            'verified' => true,
            'paidAmount' => $_GET['total_fee'],
            'paymentId' => $_GET['trade_no'],
            'orderNumber' => $_GET['subject'],
            'updateOrderStatus' => true,
            'message' => '',
            'currency' => 'CNY',
          );
          $payment_status = $_POST['trade_status'];
          /* 验证 */
          if ($payment_status == 'WAIT_SELLER_SEND_GOODS' || $payment_status == 'TRADE_FINISHED' || $payment_status == 'TRADE_SUCCESS') {
              $result['verified'] = true;
          } else {
              $result['verified'] = false;
          }           
          Log::write('alipay notice log: '.json_encode($_POST).'checkpost pass');
        } else {
          $result = array(
            'verified' => false,
          );
          Log::write('alipay notice log: REQUEST_METHOD'.$_SERVER['REQUEST_METHOD'].' '.json_encode($_REQUEST));
        }
        return $result;
    }  
}